package com.hexiang.seckill.mq;

import com.hexiang.seckill.domain.MiaoshaOrder;
import com.hexiang.seckill.domain.MiaoshaUser;
import com.hexiang.seckill.redis.RedisService;
import com.hexiang.seckill.service.GoodsService;
import com.hexiang.seckill.service.MiaoshaService;
import com.hexiang.seckill.service.OrderService;
import com.hexiang.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "seckill_order_topic_spring", consumerGroup = "${rocketmq.consumer.group}", selectorExpression = "*", selectorType = SelectorType.TAG)
public class MQReceiver implements RocketMQListener<MessageExt> {

    @Autowired
    private RedisService redisService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MiaoshaService miaoshaService;

    @Autowired
    private GoodsService goodsServiceRpc;


    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String msg = new String(body);
        log.info("接收到秒杀成功订单消息：msg={}", msg);
        MiaoshaMessage mm = RedisService.stringToBean(msg, MiaoshaMessage.class);
        MiaoshaUser user = mm.getUser();
        long goodsId = mm.getGoodsId();

        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        if (stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(Long.parseLong(user.getNickname()), goodsId);
        if (order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        miaoshaService.miaosha(user, goods);
    }


}
